package com.vitaf.cash.app.utils.helper

import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.appcompat.app.AppCompatActivity
import com.vitaf.cash.app.utils.log.VitafLog
import com.google.android.gms.tasks.Task
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.appupdate.AppUpdateOptions
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.UpdateAvailability
import com.vitaf.cash.app.common.VitafComAct

/**
 * 版本更新帮助类
 */
class VitafUpdateHp(
    private val activity: AppCompatActivity,
    private val forceUpdate: Boolean = false, // 是否需要强制更新
    private val updateLauncher: ActivityResultLauncher<IntentSenderRequest>,
    private val onForceUpdateRedirect: (() -> Unit)? = null // 可选强更跳转商店前通知
) {

    private val appUpdateManager: AppUpdateManager = AppUpdateManagerFactory.create(activity)

    /**
     * 判断是否满足立即更新启动条件
     */
    private fun AppUpdateInfo?.canStartImmediateUpdate(): Boolean =
        this?.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
                this.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)

    /**
     * 判断是否满足恢复更新流程条件
     */
    private fun AppUpdateInfo?.canResumeUpdate(): Boolean = this?.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS

    /**
     * 非协程版
     * 检查更新并启动立即更新流程
     * @param onNoUpdate 无更新时回调
     */
    fun checkAndStartUpdate(onNoUpdate: () -> Unit) {
        try {
            appUpdateManager.appUpdateInfo
                .addOnSuccessListener { info ->
                    try {
                        if (info == null || !info.canStartImmediateUpdate()) {
                            handleNoUpdate(onNoUpdate)
                            return@addOnSuccessListener
                        }

                        val started = appUpdateManager.startUpdateFlowForResult(info, updateLauncher, AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build())
                        if (!started) {
                            VitafLog.e("Google update not found")
                            handleNoUpdate(onNoUpdate)
                        }

                    } catch (e: Exception) {
                        VitafLog.e(e.localizedMessage)
                        handleNoUpdate(onNoUpdate)
                    }
                }
                .addOnFailureListener { e ->
                    VitafLog.e("addOnFailureListener error: ${e.localizedMessage}")
                    handleNoUpdate(onNoUpdate)
                }
        } catch (e: Exception) {
            VitafLog.e(e.localizedMessage)
            handleNoUpdate(onNoUpdate)
        }
    }

    /**
     * 非协程版
     * 恢复未完成的更新流程
     */
    fun resumeIfInProgress() {
        try {
            val infoTask: Task<AppUpdateInfo> = appUpdateManager.appUpdateInfo
            infoTask.addOnSuccessListener { info ->
                if (info == null) return@addOnSuccessListener
                if (info.canResumeUpdate()) {
                    try {
                        appUpdateManager.startUpdateFlowForResult(info, updateLauncher, AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build())
                    } catch (e: Exception) {
                        VitafLog.e("resume update error: ${e.localizedMessage}")
                    }
                }
            }
        } catch (e: Exception) {
            VitafLog.e("resume update error: ${e.localizedMessage}")
        }
    }

    /**
     * 跳转应用商店详情页, 目的是让用户手动更新
     */
    private fun goToPlayStorePage() {
        val packageName = activity.packageName
        try {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))
            intent.setPackage("com.android.vending")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            activity.startActivity(intent)
        } catch (e: Exception) {
            try {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName"))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                activity.startActivity(intent)
            } catch (e: Exception) {
                VitafLog.e("intent google store error: ${e.localizedMessage}")
            }
        }
    }

    /**
     * 处理回调
     */
    fun handleNoUpdate(onNoUpdate: () -> Unit) {
        try {
            if (forceUpdate) {
                onForceUpdateRedirect?.invoke()
                goToPlayStorePage()
            } else {
                onNoUpdate()
            }
        } catch (e: Exception) {
            //
        }
    }
}